<?php
header("Content-type:text/html;Charset=utf-8");
//抽象策略接口
abstract class Strategy{
    abstract function wayToSchool();
}
//具体策略角色
class BikeStrategy extends Strategy{
    function wayToSchool(){
        echo "骑自行车去上学";
    }
}
class BusStrategy extends Strategy{
    function wayToSchool(){
        echo "乘公共汽车去上学";
    }
}
class TaxiStrategy extends Strategy{
    function wayToSchool(){
        echo "骑出租车去上学";
    }
}

//环境角色
class Context{
    private $strategy;

    //通过依赖注入获取类的实例
    /* public function __construct(Strategy $objStrategy) {
        $this->strategy = $objStrategy;
        var_dump($objStrategy);
    } */

    //通过传入类名使用php反射创建实例
    //获取具体策略
    function getStrategy($strategyName){
        try{
            $strategyReflection = new ReflectionClass($strategyName); //php反射类 // 建立BusStrategy这个类的反射类
            $this->strategy = $strategyReflection->newInstance(); //创建实例 // 相当于实例化BusStrategy类
            //getMethods()       来获取到类的所有methods。
            //hasMethod(string)  是否存在某个方法
            //getMethod(string)  获取方法
            //echo "<pre/>";
            //var_dump($strategyReflection->getMethods());
        }catch(ReflectionException $e){
            $this->strategy = "";
        }
    }

    function goToSchool(){
        $this->strategy->wayToSchool();
        // var_dump($this->strategy);
    }
}

//测试依赖注入调用
/* $context = new Context(new BusStrategy());
$context->goToSchool(); */

//测试php反射调用
$context = new Context();
$context->getStrategy("BusStrategy");
$context->goToSchool();
